package com.sctvcloud.renhe.tts;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.sunflower.FlowerCollector;
import com.jiongbull.jlog.JLog;
import com.sctvcloud.renhe.R;
import com.sctvcloud.renhe.base.BaseActivity;
import com.sctvcloud.renhe.ui.activities.SearchActivity;
import com.sctvcloud.renhe.ui.activities.SpeakActivity;
import com.sctvcloud.renhe.ui.utils.JsonParser;
import com.sctvcloud.renhe.ui.utils.PermissionUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedHashMap;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class SpeachUtils {

    private BaseActivity activity;
    // 语音听写对象
    private SpeechRecognizer mIat;
    // 用HashMap存储听写结果
    private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;
    private int ret = 0; // 函数调用返回
    private String voiceTxt;
    private OnVoiceRecordListener listener;

    private PermissionUtils mPermissionUtils;

    public SpeachUtils(BaseActivity activity) {
        this.activity = activity;
        checkRecordPermission();
        mIat = SpeechRecognizer.createRecognizer(activity, null);
    }

    /**
     * 启动录音
     */
    public void startRecord() {
        mIatResults.clear();
        voiceTxt = "";
        // 设置参数
        setParam();
        ret = mIat.startListening(mRecognizerListener);
        if (ret != ErrorCode.SUCCESS) {
            toast("识别失败,错误码：" + ret);
        }
    }

    /**
     * 结束录音
     */
    public void stopRecord() {
        if (null != mIat && mIat.isListening()) {
            mIat.stopListening();
        }
        FlowerCollector.onPageEnd("");
        FlowerCollector.onPause(activity);
    }

    private void checkRecordPermission() {
        mPermissionUtils = new PermissionUtils(activity);
        mPermissionUtils.addPermission(Manifest.permission.RECORD_AUDIO);

        mPermissionUtils.setPermissionListener(new PermissionUtils.PermissionListener() {
            @Override
            public void onUserRefusesPermissions() {
                toast("用户拒绝了权限，无法使用录音功能, 如需重新授予权限，请进入手机的“设置-应用程序-SiChuanFocus2Android”中打开权限");
            }
        });

        if (mPermissionUtils.checkAndRequestPermissions()) {
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            toast("用户拒绝了权限，无法使用录音功能, 如需重新授予权限，请进入手机的“设置-应用程序-SiChuanFocus2Android”中打开权限");
        }
    }

    public void destroy() {
        if (null != mIat) {
            // 退出时释放连接
            mIat.cancel();
            mIat.destroy();
        }
    }
    public void toast(String str) {
        if (TextUtils.isEmpty(str)) {
            return;
        }
        Toast.makeText(activity, str, Toast.LENGTH_SHORT).show();
    }

    /**
     * 参数设置
     *
     * @param
     * @return
     */
    public void setParam() {
        // 清空参数
        mIat.setParameter(SpeechConstant.PARAMS, null);

        // 设置听写引擎
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
        // 设置返回结果格式
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");

        // 设置语言
        mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        // 设置语言区域
        mIat.setParameter(SpeechConstant.ACCENT, "mandarin");

        mIat.setParameter(SpeechConstant.VAD_BOS, "4000");

        mIat.setParameter(SpeechConstant.VAD_EOS, "3000");
    }

    private void printResult(RecognizerResult results) {
        String text = JsonParser.parseIatResult(results.getResultString());
        String sn = null;
        // 读取json结果中的sn字段
        try {
            JSONObject resultJson = new JSONObject(results.getResultString());
            sn = resultJson.optString("sn");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mIatResults.put(sn, text);

        StringBuffer resultBuffer = new StringBuffer();
        for (String key : mIatResults.keySet()) {
            resultBuffer.append(mIatResults.get(key));
        }
        voiceTxt = resultBuffer.toString();
        if (null != listener) {
            listener.OnRecordBack(voiceTxt);
            destroy();
        }
    }

    /**
     * 语音听写监听器
     */
    private RecognizerListener mRecognizerListener = new RecognizerListener() {

        @Override
        public void onBeginOfSpeech() {
        }

        @Override
        public void onError(SpeechError error) {
            //  toast(error + "");
        }

        @Override
        public void onEndOfSpeech() {
        }

        @Override
        public void onResult(RecognizerResult results, boolean isLast) {
            printResult(results);
        }

        @Override
        public void onVolumeChanged(int volume, byte[] data) {
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {

        }
    };

    public OnVoiceRecordListener getListener() {
        return listener;
    }

    public void setVoiceRecordListener(OnVoiceRecordListener listener) {
        this.listener = listener;
    }

    public interface OnVoiceRecordListener {
        void OnRecordBack(String txt);
    }


}
